﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JESAI.Core.Util.Extensions.Strings;
using JESAI.Application.Abstractions.Sys;
using JESAI.Application.Abstractions.Sys.Dtos;
using Newtonsoft.Json;

namespace JESAI.Framework.Filters
{
    public class HttpResponseFilter : IActionFilter
    {
        private readonly ILogger<HttpResponseFilter> _logger;
        private readonly IAuditLogService _auditLogService;
        public HttpResponseFilter(ILogger<HttpResponseFilter> logger, IAuditLogService auditLogService)
        {
            _logger = logger;
            _auditLogService = auditLogService;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var connectionId = string.Empty;
            long constTime = 0;
            if (context.HttpContext.Items.ContainsKey("stopWatch"))
            {
                Stopwatch stopWatch = (Stopwatch)context.HttpContext.Items["stopWatch"];
                stopWatch?.Stop();
                constTime = stopWatch.ElapsedMilliseconds;
            }

            if (context.HttpContext.Items.ContainsKey("connectionId"))
            {
                connectionId = (string)context.HttpContext.Items["connectionId"];
            }

            if (!connectionId.IsNullOrEmptyOrWhiteSpace())
            {
                // 在 Action 执行后执行的逻辑
                var result = context.Result;

                AuditLogDto auditLogDto = new AuditLogDto();
                auditLogDto.ConnectionId = connectionId;
                auditLogDto.RequestHandleTime = constTime;
                var responseParams = JsonConvert.SerializeObject(result);
                auditLogDto.ResponseParams = responseParams.Length < 4000 ? responseParams : responseParams.Substring(0, 4000);
                auditLogDto.ResponseTime = DateTime.Now;

                _auditLogService.UpdateAuditLogAsync(auditLogDto);

            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {

        }
    }
}
